package com.webchat.admin.service;


import com.webchat.admin.config.CallbackEncryptKeyConfig;
import com.webchat.common.enums.payment.PaymentBusinessActionEnum;
import com.webchat.common.util.AESEncryptUtil;
import com.webchat.common.util.JsonUtil;
import com.webchat.domain.dto.payment.CallBackRequestBodyDTO;
import com.webchat.domain.dto.payment.PaymentCallbackEncryptBody;
import com.webchat.domain.dto.payment.PaymentResultDTO;
import com.webchat.rmi.ugc.UgcCallBackClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class CallBackService {

    @Autowired
    private CallbackEncryptKeyConfig callbackEncryptKeyConfig;

    @Autowired
    private UgcCallBackClient ugcCallBackClient;

    private static final String PGC_SERVER = "WEBCHAT_PGC";

    private static final String UGC_SERVER = "WEBCHAT_UGC";

    public void webchatPaymentCallBack(PaymentCallbackEncryptBody paymentCallbackEncryptBody) {
        log.info("收到 webchat-pay 支付结果回调 ===> 密文：{}", paymentCallbackEncryptBody.getMessage());
        // 异步来处理回调结果
        PaymentResultDTO callBackRequestBody = this.decryptMessage(paymentCallbackEncryptBody.getMessage());
        log.info("收到 webchat-pay 支付结果回调 ===> 明文：{}", JsonUtil.toJsonString(callBackRequestBody));
        CallBackRequestBodyDTO callBackBody = callBackRequestBody.getData();
        PaymentBusinessActionEnum businessAction = PaymentBusinessActionEnum.getByAction(callBackBody.getBusinessAction());
        if (businessAction == null) {
            return;
        }

        if (UGC_SERVER.equals(businessAction.getServer())) {
            ugcCallBackClient.paymentCallBack(callBackRequestBody);
        } else if (PGC_SERVER.equals(businessAction.getServer())) {
            // TODO
        } else {
            log.warn("支付回调处理失败 ====> 不支持的回调服务！callBack Server:{}", businessAction.getServer());
            return;
        }

    }

    private PaymentResultDTO decryptMessage(String message) {
        if (StringUtils.isBlank(message)) {
            return null;
        }
        String decryptMessage = AESEncryptUtil.decrypt(message, callbackEncryptKeyConfig.getPayment());
        return JsonUtil.fromJson(decryptMessage, PaymentResultDTO.class);
    }
}
